package cloud.coder.remote.grpc.server.handler;

import cloud.coder.remote.grpc.server.GRPCHandler;
import io.grpc.examples.msg.report.MsgCollection;
import io.grpc.examples.msg.report.MsgObject;
import io.grpc.examples.msg.report.MsgReportServiceGrpc;
import io.grpc.examples.network.common.Commands;
import io.grpc.stub.StreamObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MsgReportServiceHandler extends MsgReportServiceGrpc.MsgReportServiceImplBase implements GRPCHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(MsgReportServiceHandler.class);


    public MsgReportServiceHandler() {
    }

    @Override
    public StreamObserver<MsgObject> report(StreamObserver<Commands> responseObserver) {
        return new StreamObserver<MsgObject>() {
            @Override
            public void onNext(MsgObject msgObject) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("received msg in streaming");
                }
                try {
                    LOGGER.info(msgObject.toString());
                } catch (Exception e) {
                    //TODO
                } finally {
                    //TODO
                }
            }

            @Override
            public void onError(Throwable throwable) {
                LOGGER.error(throwable.getMessage(), throwable);
                responseObserver.onCompleted();
            }

            @Override
            public void onCompleted() {
                responseObserver.onNext(Commands.newBuilder().build());
                responseObserver.onCompleted();
            }
        };
    }

    @Override
    public void reportInSync(final MsgCollection request, final StreamObserver<Commands> responseObserver) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("received {} msgs", request.getMsgsCount());
        }

        request.getMsgsList().forEach(msgObject -> {
            try {
                LOGGER.info(msgObject.toString());
            } catch (Exception e) {
                //TODO
            } finally {
                //TODO
            }
        });

        responseObserver.onNext(Commands.newBuilder().build());
        responseObserver.onCompleted();
    }
}
